﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SFast;
using SolutionModel;
using SolutionBLL;

namespace SWebAction
{
    public class Action : System.Web.UI.Adapters.PageAdapter
    {
        private static readonly Hashtable s_table = Hashtable.Synchronized(new Hashtable());
        //获取某个类中的所有函数
        private static MethodInfo[] GetMethodInfo(Type type)
        {
            return type.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(o => o.DeclaringType == type).ToArray();
        }


        //执行OnLoad 
        protected override void OnLoad(EventArgs e)
        {
            //判断本次请求，是否为后台，admin文件夹下页面

            //本次请求的页面的所在的文件路径
            //"G:\\工作所需\\架构\\权限系统\\1.0.0_2012.5.28\\Solution\\WebSite\\admin\\webconfig\\navbar.aspx"
            //获取到admin\\webconfig\\navbar.aspx"
            String pagePath = Page.Request.PhysicalPath.Replace(Page.Request.PhysicalApplicationPath, "");
            if (String.IsNullOrEmpty(pagePath))
            {
                return;
            }
            String[] pagePaths = pagePath.Split('\\');
            if (pagePaths.Length==0)
            {
                return;
            }
            if (pagePaths[0].ToLower() == "admin")
            {
                MyUserLogin ul = new MyUserLogin();
                //当用户没有登录时跳转到登录页
                if (!ul.LoginState)
                {
                    //如果本次请求地址为登录页不做跳转，防止死循环
                    if (!Page.Request.Url.AbsolutePath.Contains("/admin/login.aspx"))
                    {
                        Page.Response.Redirect("/admin/login.aspx");
                    }
                }
            }
            

            Page.Error += new EventHandler(Error);

            //权限控制判断是否有查看当前页面的权限
            //Privilege.Page();

            base.OnLoad(e);

            //以表单中的fun为主;
            //如果没有获取url中的
            String action = String.IsNullOrEmpty(Page.Request.Form["fun"])
                                    ? Page.Request.QueryString["fun"]
                                    : Page.Request.Form["fun"];

            //如果都没有，以下不执行
            if (String.IsNullOrEmpty(action))
                return;

            //获取所有函数
            var array = GetMethodInfo(Page.GetType().BaseType);

            //没有函数不执行
            if (array.Length == 0)
                return;

            //通fun 获取函数信息
            var method = array.FirstOrDefault(o => o.Name.Equals(action, StringComparison.CurrentCultureIgnoreCase));
            if (method != null)
            {
                object ro = method.Invoke(Page, null);  //执行函数
                if (ro != null)
                {
                    Page.Response.Write(ro);
                    Page.Response.End();
                }
            }
        }


        /// <summary>
        /// 把文本响应给请求者之前拦截文本，用DefaultFilterResponse筛选器，进行筛选
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            var Response = System.Web.HttpContext.Current.Response;
            Response.Filter = new DefaultFilterResponse(Response.Filter);
            base.Render(writer);
        }

        protected override void EndRender(System.Web.UI.HtmlTextWriter writer)
        {
            base.EndRender(writer); 
        }

        #region 当发生错误时处理信息
        /// <summary>
        /// 当发生错误时处理信息
        /// 错误的记录的使用，是把错误抛出来由此事件接收并处理
        /// 可以提供提示模板
        /// throw new Exception(MyJs.GetAlertStr("出错了，错误详细：{0}","/admin/index.aspx"), ex);  //弹框的模板
        /// throw new Exception(MyJs.GetRedirectJsStr("/admin/index.aspx"), ex);  //地址跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Error(object sender, EventArgs e)
        {
            T_Error error = null;
            Exception ex = Page.Server.GetLastError();
            Exception exc = ex.InnerException;
            //记得错误信息，后期在做
            if (ex.InnerException != null)
            {
                error = new T_Error();

                error.Title = exc.Message;
                error.Url = Page.Request.RawUrl;
                error.ErrorType = exc.GetBaseException().GetType().FullName;
                error.Record = exc.StackTrace.Replace("\r\n", "<br />").Trim();
                error.CreateTime = DateTime.Now;
            }
            else
            {
                error = new T_Error();
                error.Title = ex.Message;
                error.Url = Page.Request.RawUrl;
                error.ErrorType = ex.GetBaseException().GetType().FullName;
                error.Record = ex.StackTrace.Replace("\r\n", "<br />").Trim();
                error.CreateTime = DateTime.Now;
            }
            if (error != null)
            {
                T_ErrorBLL bll = new T_ErrorBLL();
                bll.Add(error);
                Page.Server.ClearError();
            }

            Page.Response._WriteEnd(ex.Message._Format(exc == null ? "" : exc.Message));
        }
        #endregion

    }
}
